//
//  HMDiscoverSearchView.swift
//  WeiBo14
//
//  Created by HM on 16/3/2.
//  Copyright © 2016年 HM. All rights reserved.
//

import UIKit

/**
 IBInspectable: 其用于修饰属性,其修饰的属性可以在 xib 右边的控制面板里面显示
 
 IBDesignable: 其用于修饰自定义view
 
 */


class HMDiscoverSearchView: UIView {

    // 右边的约束
    @IBOutlet weak var textFieldRightCons: NSLayoutConstraint!
    // 输入框
    @IBOutlet weak var textfield: UITextField!
    // 取消按钮
    @IBOutlet weak var cancelButton: UIButton!

    
    class func searchView() -> HMDiscoverSearchView {
        // 双 mainbundle 里面加载 view
        return NSBundle.mainBundle().loadNibNamed("HMDiscoverSearchView", owner: nil, options: nil).last! as! HMDiscoverSearchView
    }
    
    override func awakeFromNib() {
        
        // 在这里面设置 leftView是可以的
        // 因为在这个方法里面 textField 是有值的
        
        leftView.frame.size = CGSize(width: self.frame.height, height: self.frame.height)
        textfield.leftView = leftView
        textfield.leftViewMode = .Always
        
        
//        textfield.layer.borderWidth
//        textfield.layer.borderColor = UIColor.redColor().CGColor
//        textfield.layer.cornerRadius = 5
//        textfield.layer.masksToBounds = true
        
    }
    
//    required init?(coder aDecoder: NSCoder) {
//        super.init(coder: aDecoder)
//        print("哈哈")
//    }

    @IBAction func editingDidBegin(sender: UITextField) {
        print("开始编辑了哈哈")
        // 1. 调整右边约束
        // 执行约束动画,把调整约束的代码放到动画的block里面是不好使
        // 需要调用 layoutIfNeeded()
        self.textFieldRightCons.constant = self.cancelButton.frame.width
        UIView.animateWithDuration(0.25) { () -> Void in
            self.layoutIfNeeded()
        }
    }
    
    
    @IBAction func cancelButtonClick(sender: UIButton) {
        print("取消按钮点击")
        // 1. 调整右边约束
        textFieldRightCons.constant = 0
        // 2. 取消textField的第一响应者
        textfield.resignFirstResponder()
        
        UIView.animateWithDuration(0.25) { () -> Void in
            self.textfield.layoutIfNeeded()
        }
    }
    
    
    // MARK: - 懒加载控件
    
    private lazy var leftView: UIImageView = {
        let view = UIImageView(image: UIImage(named: "searchbar_textfield_search_icon"))
        // 设置 内容模式
        view.contentMode = .Center
        return view
    }()
    
}
